package com.nineclock.auth.config;

import com.nineclock.auth.exception.NcWebResponseExceptionTranslator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.sql.DataSource;

@Configuration
@EnableAuthorizationServer  //开启 认证服务
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
	
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
  
    //配置客户端的详情信息（客户端的身份）
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//        clients.inMemory()
//                //配置客户端的标识
//                .withClient("nc_client_app")  //客户端 id
//                .secret(passwordEncoder.encode("123456"))     // 客户端 密钥
//                .scopes("all")  //授权的范围
//                .redirectUris("http://localhost") // 认证通过的 重定向路径
//                .authorizedGrantTypes("authorization_code","password") //授权模型（授权码 ， 密码验证）
//                .and()
//                .withClient("nc_client_pc")
//                .secret(passwordEncoder.encode("123456"))
//                .scopes("all")
//                .redirectUris("http://localhost")
//                .authorizedGrantTypes("authorization_code","password");
        clients.withClientDetails(clientDetailsService());
    }
    @Autowired
    DataSource dataSource;

    @Bean
    public ClientDetailsService clientDetailsService(){
        return new JdbcClientDetailsService(dataSource);
    }

    /**
     * 对  /oauth/authorize  /oauth/token 两个路径进行放行
     * @param security
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.tokenKeyAccess("permitAll") //tokenkey当使用JwtToken且使用非对称加密时，资源服务用于获取公钥而开放的，这里指这个 endpoint(/oauth/token )完全公开
                .checkTokenAccess("permitAll") //checkToken这个endpoint(/oauth/authorize) 完全公开
                .allowFormAuthenticationForClients(); //允许表单认证(密码/授权码模式认证)
    }

    @Autowired
    TokenStore tokenStore;

    @Autowired
    ClientDetailsService clientDetailsService;

    @Autowired
    JwtAccessTokenConverter jwtAccessTokenConverter;

    /**
     * 配置 token 的详细信息
     * @return
     */
    @Bean
    public AuthorizationServerTokenServices tokenServices(){
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore); //token的存储对象
        tokenServices.setClientDetailsService(clientDetailsService); //客户端详情服务
        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 30); //刷新token的有效期
        tokenServices.setAccessTokenValiditySeconds( 60 * 60 * 12); //token的有效期
        //token 增强对象
        tokenServices.setTokenEnhancer(jwtAccessTokenConverter);
        return tokenServices;
    }

    @Autowired
    AuthenticationManager authenticationManager;

    /**
     *
     * @param endpoints 端点
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.exceptionTranslator(new NcWebResponseExceptionTranslator()) //异常转换
                .tokenServices(tokenServices())
                .authenticationManager(authenticationManager)
                .allowedTokenEndpointRequestMethods(HttpMethod.POST);
    }

}